package com.song.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.server.dto.EmployeeParam;
import com.song.server.entity.Employee;
import com.song.server.mapper.EmployeeMapper;
import com.song.server.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.server.vo.RespBean;
import com.song.server.vo.RespPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author inkolopolookni
 * @since 2021-10-19
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public RespPageBean getAllEmployeesByPage(EmployeeParam employeeParam) {
        Integer currentPage = (employeeParam.getCurrentPage() != null) ? employeeParam.getCurrentPage() : 1;
        Integer size = (employeeParam.getSize() != null) ? employeeParam.getSize() : 10;
        // 开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> employeePage = employeeMapper.getAllEmployeesByPage(page, employeeParam);
        return new RespPageBean(employeePage.getTotal(), employeePage.getRecords());
    }

    @Override
    public RespBean maxWorkID() {
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workId)"));
        Integer maxWorkId = Integer.parseInt(maps.get(0).get("max(workId)").toString());
        return RespBean.success(null, String.format("%08d", maxWorkId + 1));
    }

    @Override
    public RespBean addEmployee(Employee employee) {
        // 1. 先计算合同时间
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.0)));

        if (1 == employeeMapper.insert(employee)) {
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");
    }
}
